1337C - Linova and Kingdom - CodeForces Solution


dfs and similar dp greedy sortings trees *1600

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>

using namespace std;


typedef long long ll;
typedef long int li;
typedef long double ld;
typedef vector<int> vi;
typedef vector<long long> vll;
typedef vector<vector<int>> vvi;
typedef pair<int,int> pii;
//typedef long long int;

#define endl "\n"
#define f(i,a,b) for(int i=a;i<=(b);i++)
#define r(i,a,b) for(int i=a;i>=(b);i--)
#define ff first
#define ss second
#define all(a) a.begin(), a.end()
#define mid(s,l) (s+(l-s)/2)
#define umap unordered_map
#define pb push_back
#define mp make_pair
//#define int long long

//const int INF = int(1e9);
//const int MOD = int(1e9) + 7;
//const ld EPS = 1e-18;
//const ld PI = acos(-1.0); 

const int N = 2e5 + 3;
vector<vector<int>> adj(N);
vector<int> con;
vector<int> depth(N);
int dfs(int vert , int par){
	depth[vert] = depth[par] + 1;
	int val = 0;
	for(auto child : adj[vert]){
		if(child == par) continue;
		val += dfs(child , vert);
	}
	con.pb(depth[vert] - 1 - val);
	//cout << vert << ' ' << val << ' ' << depth[vert] - 1 - val << endl;
	return val + 1;	
}

void GG()
{
	adj.clear();
	con.clear();
	depth.clear();
	int n;
	cin >> n;
	adj.resize(n + 3);
	depth.resize(n + 3);
	int k;
	cin >> k;
	for(int i = 2; i <= n; i++){
		int u , v;
		cin >> u >> v;
		adj[u].pb(v);
		adj[v].pb(u);
	}
	dfs(1 , 0);
	sort(all(con) , greater<int>());
	ll tot = 0;
	for(int i = 0; i < k; i++)
		tot += (ll) con[i];
	cout << tot << endl;
}

signed main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	int ttc=1;
	//cin>>ttc;
	//int cnt=0;
	while(ttc--)
	{
		//cout<<"Case "<<++cnt<<": ";
		GG();
	}
}
			 	 	 			  		 				   			


Comments

Submit
0 Comments
More Questions

1217. Minimum Cost to Move Chips to The Same Position
347. Top K Frequent Elements
1503. Last Moment Before All Ants Fall Out of a Plank
430. Flatten a Multilevel Doubly Linked List
1290. Convert Binary Number in a Linked List to Integer
1525. Number of Good Ways to Split a String
72. Edit Distance
563. Binary Tree Tilt
1306. Jump Game III
236. Lowest Common Ancestor of a Binary Tree
790. Domino and Tromino Tiling
878. Nth Magical Number
2099. Find Subsequence of Length K With the Largest Sum
1608A - Find Array
416. Partition Equal Subset Sum
1446. Consecutive Characters
1618A - Polycarp and Sums of Subsequences
1618B - Missing Bigram
938. Range Sum of BST
147. Insertion Sort List
310. Minimum Height Trees
2110. Number of Smooth Descent Periods of a Stock
2109. Adding Spaces to a String
2108. Find First Palindromic String in the Array
394. Decode String
902. Numbers At Most N Given Digit Set
221. Maximal Square
1200. Minimum Absolute Difference
1619B - Squares and Cubes
1619A - Square String